<template>
	<view class="search-container">
		<!-- 搜索头部 -->
		<view class="search-header">
			<view class="search-input-box">
				<view class="search-icon">
					<text class="iconfont icon-search"></text>
				</view>
				<input 
					class="search-input" 
					v-model="searchKeyword"
					placeholder="请输入商品名称"
					placeholder-style="color: #999;"
					@confirm="handleSearch"
					@input="onInputChange"
					focus
				/>
				<view class="clear-btn" v-if="searchKeyword" @tap="clearSearch">
					<text class="iconfont icon-close"></text>
				</view>
			</view>
			<view class="cancel-btn" @tap="goBack">{{ searchKeyword ? '清空' : '取消' }}</view>
		</view>

		<!-- 搜索内容区域 -->
		<view class="search-content">
			<!-- 搜索历史 -->
			<view class="search-history" v-if="!searchKeyword && searchHistory.length > 0">
				<view class="section-title">
					<text>搜索历史</text>
					<view class="clear-history" @tap="clearHistory">
						<text class="iconfont icon-delete"></text>
					</view>
				</view>
				<view class="history-tags">
					<view 
						class="history-tag" 
						v-for="(item, index) in searchHistory" 
						:key="index"
						@tap="selectHistory(item)"
					>
						{{ item }}
					</view>
				</view>
			</view>

			<!-- 热门搜索 -->
			<view class="hot-search" v-if="!searchKeyword">
				<view class="section-title">
					<text>热门搜索</text>
				</view>
				<view class="hot-tags">
					<view 
						class="hot-tag" 
						v-for="(item, index) in hotSearchList" 
						:key="index"
						@tap="selectHotSearch(item)"
					>
						{{ item }}
					</view>
				</view>
			</view>

			<!-- 推荐商品 -->
			<view class="recommend-goods" v-if="!searchKeyword">
				<view class="section-title">
					<text>推荐商品</text>
				</view>
				<view class="goods-name-list">
					<view 
						class="goods-name-item" 
						v-for="(item, index) in recommendGoods" 
						:key="index"
						@tap="goToGoodsDetail(item)"
					>
						<text class="goods-name-text">{{ item.name }}</text>
						<text class="goods-price-text">¥{{ item.price }}</text>
					</view>
				</view>
			</view>

			<!-- 搜索结果 -->
			<view class="search-results" v-if="searchKeyword && searchResults.length > 0">
				<view class="result-count">找到 {{ totalCount }} 个相关商品</view>
				<view class="goods-list">
					<view 
						class="goods-item" 
						v-for="(item, index) in searchResults" 
						:key="index"
						@tap="goToGoodsDetail(item)"
					>
						<image class="goods-image" :src="item.img" mode="aspectFill"></image>
						<view class="goods-info">
							<view class="goods-name">{{ item.name }}</view>
							<view class="goods-price">
								<text class="price-symbol">¥</text>
								<text class="price-value">{{ item.price }}</text>
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 无搜索结果 -->
			<view class="no-result" v-if="searchKeyword && searchResults.length === 0 && !loading">
				<image class="no-result-image" src="/static/img/noorder.png" mode="aspectFit"></image>
				<view class="no-result-text">没有找到相关商品</view>
				<view class="no-result-tips">试试其他关键词吧</view>
			</view>

			<!-- 加载中 -->
			<view class="loading" v-if="loading">
				<text>搜索中...</text>
			</view>
		</view>
	</view>
</template>

<script>
import goodsApi from '@/utils/goods.js'

export default {
	data() {
		return {
			searchKeyword: '',
			searchHistory: [],
			hotSearchList: ['手机', '电脑', '服装', '食品', '家电', '数码', '美妆', '运动'],
			recommendGoods: [],
			searchResults: [],
			loading: false,
			totalCount: 0,
			page: 1,
			pageSize: 20
		}
	},
	onLoad() {
		this.loadSearchHistory()
		this.loadRecommendGoods()
	},
	methods: {
		// 取消搜索
		goBack() {
			this.searchKeyword = ''
			this.searchResults = []
		},

		// 输入变化
		onInputChange(e) {
			this.searchKeyword = e.detail.value
		},

		// 清空搜索
		clearSearch() {
			this.searchKeyword = ''
			this.searchResults = []
		},

		// 执行搜索
		async handleSearch() {
			if (!this.searchKeyword.trim()) {
				uni.showToast({
					title: '请输入搜索关键词',
					icon: 'none'
				})
				return
			}

			this.loading = true
			this.page = 1
			
			try {
				const res = await goodsApi.searchGoods({
					keyword: this.searchKeyword
				})

				if (res && res.code === 200) {
					// 后端直接返回商品数组，不是 {list: [], total: 0} 结构
					this.searchResults = res.data || []
					this.totalCount = this.searchResults.length
					
					// 保存搜索历史
					this.saveSearchHistory(this.searchKeyword)
				} else {
					// 如果后端API未实现，使用测试数据
					console.log('后端API未返回数据，使用测试数据')
					this.searchResults = this.getTestData()
					this.totalCount = this.searchResults.length
					
					// 保存搜索历史
					this.saveSearchHistory(this.searchKeyword)
				}
			} catch (error) {
				console.error('搜索失败:', error)
				// 如果API调用失败，使用测试数据
				console.log('API调用失败，使用测试数据')
				this.searchResults = this.getTestData()
				this.totalCount = this.searchResults.length
				
				// 保存搜索历史
				this.saveSearchHistory(this.searchKeyword)
			} finally {
				this.loading = false
			}
		},

		// 获取测试数据
		getTestData() {
			const testData = [
				{
					id: 1,
					name: '苹果iPhone 15 Pro Max',
					price: 9999,
					imgPath: '/static/img/goods/p1.jpg'
				},
				{
					id: 2,
					name: '华为Mate 60 Pro',
					price: 6999,
					imgPath: '/static/img/goods/p2.jpg'
				},
				{
					id: 3,
					name: '小米14 Ultra',
					price: 6499,
					imgPath: '/static/img/goods/p3.jpg'
				},
				{
					id: 4,
					name: 'OPPO Find X7 Ultra',
					price: 5999,
					imgPath: '/static/img/goods/p4.jpg'
				},
				{
					id: 5,
					name: 'vivo X100 Pro',
					price: 5999,
					imgPath: '/static/img/goods/p5.jpg'
				}
			]
			
			// 根据关键词过滤
			return testData.filter(item => 
				item.name.toLowerCase().includes(this.searchKeyword.toLowerCase())
			)
		},

		// 选择历史记录
		selectHistory(keyword) {
			this.searchKeyword = keyword
			this.handleSearch()
		},

		// 选择热门搜索
		selectHotSearch(keyword) {
			this.searchKeyword = keyword
			this.handleSearch()
		},

		// 跳转到商品详情
		goToGoodsDetail(item) {
			uni.navigateTo({
				url: `/pages/goods/goods?id=${item.id}`
			})
		},

		// 保存搜索历史
		saveSearchHistory(keyword) {
			let history = uni.getStorageSync('searchHistory') || []
			
			// 移除重复项
			history = history.filter(item => item !== keyword)
			
			// 添加到开头
			history.unshift(keyword)
			
			// 限制数量
			if (history.length > 10) {
				history = history.slice(0, 10)
			}
			
			uni.setStorageSync('searchHistory', history)
			this.searchHistory = history
		},

		// 加载搜索历史
		loadSearchHistory() {
			this.searchHistory = uni.getStorageSync('searchHistory') || []
		},

		// 清空搜索历史
		clearHistory() {
			uni.showModal({
				title: '提示',
				content: '确定要清空搜索历史吗？',
				success: (res) => {
					if (res.confirm) {
						uni.removeStorageSync('searchHistory')
						this.searchHistory = []
					}
				}
			})
		},

		// 加载推荐商品
		async loadRecommendGoods() {
			try {
				const res = await goodsApi.getRecommendGoods()
				if (res && res.code === 200 && res.data && res.data.length > 0) {
					// 随机选择6个商品显示
					const shuffled = this.shuffleArray([...res.data])
					this.recommendGoods = shuffled.slice(0, 6)
				} else {
					// 如果API失败，使用默认数据
					this.recommendGoods = this.getDefaultRecommendGoods()
				}
			} catch (error) {
				console.error('获取推荐商品失败:', error)
				// 如果API调用失败，使用默认数据
				this.recommendGoods = this.getDefaultRecommendGoods()
			}
		},

		// 数组随机排序
		shuffleArray(array) {
			const shuffled = [...array]
			for (let i = shuffled.length - 1; i > 0; i--) {
				const j = Math.floor(Math.random() * (i + 1))
				;[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]]
			}
			return shuffled
		},

		// 获取默认推荐商品（备用数据）
		getDefaultRecommendGoods() {
			return [
				{
					id: 1,
					name: '苹果iPhone 15 Pro Max',
					price: 9999
				},
				{
					id: 2,
					name: '华为Mate 60 Pro',
					price: 6999
				},
				{
					id: 3,
					name: '小米14 Ultra',
					price: 6499
				},
				{
					id: 4,
					name: 'OPPO Find X7 Ultra',
					price: 5999
				},
				{
					id: 5,
					name: 'vivo X100 Pro',
					price: 5999
				},
				{
					id: 6,
					name: 'MacBook Pro 14英寸',
					price: 14999
				}
			]
		}
	}
}
</script>

<style lang="scss" scoped>
.search-container {
	background-color: #f5f5f5;
	min-height: 100vh;
}

.search-header {
	display: flex;
	align-items: center;
	padding: 20rpx;
	background-color: #fff;
	border-bottom: 1rpx solid #eee;
}

.search-input-box {
	flex: 1;
	display: flex;
	align-items: center;
	background-color: #f8f8f8;
	border-radius: 50rpx;
	padding: 0 20rpx;
	margin-right: 20rpx;
}

.search-icon {
	margin-right: 10rpx;
	color: #999;
}

.search-input {
	flex: 1;
	height: 70rpx;
	font-size: 28rpx;
}

.clear-btn {
	padding: 10rpx;
	color: #999;
}

.cancel-btn {
	font-size: 28rpx;
	color: #666;
}

.search-content {
	padding: 20rpx;
}

.section-title {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20rpx;
	font-size: 28rpx;
	font-weight: bold;
	color: #333;
}

.clear-history {
	color: #999;
	font-size: 24rpx;
}

.history-tags, .hot-tags {
	display: flex;
	flex-wrap: wrap;
	gap: 20rpx;
	margin-bottom: 40rpx;
}

.history-tag, .hot-tag {
	padding: 15rpx 25rpx;
	background-color: #fff;
	border-radius: 25rpx;
	font-size: 24rpx;
	color: #666;
	border: 1rpx solid #eee;
}

.hot-tag {
	background-color: #f06c7a;
	color: #fff;
	border-color: #f06c7a;
}

.goods-name-list {
	display: flex;
	flex-direction: column;
	gap: 15rpx;
}

.goods-name-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx;
	background-color: #fff;
	border-radius: 10rpx;
	border: 1rpx solid #eee;
	transition: all 0.3s ease;
}

.goods-name-item:active {
	background-color: #f8f8f8;
	transform: scale(0.98);
}

.goods-name-text {
	font-size: 28rpx;
	color: #333;
	flex: 1;
}

.goods-price-text {
	font-size: 26rpx;
	color: #f06c7a;
	font-weight: bold;
	margin-left: 20rpx;
}

.search-history, .hot-search, .recommend-goods {
	margin-bottom: 40rpx;
}

.result-count {
	font-size: 24rpx;
	color: #999;
	margin-bottom: 20rpx;
}

.goods-list {
	display: flex;
	flex-direction: column;
	gap: 20rpx;
}

.goods-item {
	display: flex;
	background-color: #fff;
	border-radius: 10rpx;
	padding: 20rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.goods-image {
	width: 120rpx;
	height: 120rpx;
	border-radius: 8rpx;
	margin-right: 20rpx;
}

.goods-info {
	flex: 1;
	display: flex;
	flex-direction: column;
	justify-content: space-between;
}

.goods-name {
	font-size: 28rpx;
	color: #333;
	line-height: 1.4;
	overflow: hidden;
	text-overflow: ellipsis;
	display: -webkit-box;
	-webkit-line-clamp: 2;
	-webkit-box-orient: vertical;
}

.goods-price {
	display: flex;
	align-items: baseline;
}

.price-symbol {
	font-size: 24rpx;
	color: #f06c7a;
}

.price-value {
	font-size: 32rpx;
	font-weight: bold;
	color: #f06c7a;
}

.no-result {
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 100rpx 0;
}

.no-result-image {
	width: 200rpx;
	height: 200rpx;
	margin-bottom: 30rpx;
}

.no-result-text {
	font-size: 28rpx;
	color: #333;
	margin-bottom: 10rpx;
}

.no-result-tips {
	font-size: 24rpx;
	color: #999;
}

.loading {
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 100rpx 0;
	color: #999;
	font-size: 28rpx;
}
</style>
